<template>
  <div class="edit-page">
    <h1>在此记录故事</h1>
    <el-form
      ref="ruleFormRef"
      :model="blog"
      :rules="rules"
      status-icon
    >
      <el-form-item label="标题：" prop="title">
        <el-input v-model="blog.title" maxlength="20"/>
      </el-form-item>
      <el-form-item label="文章类型：" prop="type">
        <el-radio-group v-model="blog.type">
          <el-radio label="学术" />
          <el-radio label="生活" />
          <el-radio label="锚点" />
        </el-radio-group>
      </el-form-item>
      <el-form-item label="封面：" prop="coverStatus">
        <cover-upload ref="cover" :blog="blog" @receiveCoverStatus="getCoverStatus" />
      </el-form-item>
      <el-form-item label="摘要" prop="description">
        <el-input v-model="blog.description" type="textarea" />
      </el-form-item>
      <el-form-item label="内容" prop="content">
        <md-editor v-model="blog.content" @onUploadImg="mdUpload" @onHtmlChanged="mdHtml" />
      </el-form-item>
      <div class="buttons">
        <el-button type="primary" @click="submitForm(ruleFormRef)">提交</el-button>
        <el-button @click="resetForm(ruleFormRef)">重置</el-button>
      </div>
    </el-form>
  </div>
</template>

<script>
import CoverUpload from '@/components/Upload/CoverUpload.vue'
import { reactive, ref } from '@vue/reactivity'
import { ElMessage, ElMessageBox } from 'element-plus'
import MdEditor from 'md-editor-v3'//文档地址https://github.com/imzbf/md-editor-v3/
import 'md-editor-v3/lib/style.css'
import axios from 'axios'
import router from '@/router'

export default {
  name: 'EditPage',
  components: { 
    CoverUpload,
    MdEditor
  },
  setup() {
    let ruleFormRef = ref(null)//好像可以绑定标签操作dom
    let cover = ref(null)//cover组件的dom
    let coverStatus = false//是否上传封面(不用响应式)
    let blog = reactive({
      title: '',
      type: '',
      description: '',
      content: '',
      html: ''
    })
    const rules = {
      title: [
        { required: true, message: '请输入标题', trigger: 'blur' },
        { min: 0, max: 15, message: '标题长度不得超过15个字符', trigger: 'blur' }
      ],
      type: [
        { required: true, message: '请选择文章类型' }
      ],
      description: [
        { min: 0, max: 50, message: '摘要最多50字', trigger: 'blur' }
      ],
      content: [
        { required: true, message: '请填写文章内容', trigger: 'blur' },
        { min: 0, max: 15000, message: '文章内容最多1万5千字', trigger: 'blur' }
      ]
    }

    const submitForm = async (ruleFormRef) => {//用async可能是为了严谨一些吧，等promise出结果才结束函数
      await ruleFormRef.validate((valid) => {
        if(!coverStatus) {
          ElMessage.error('请上传封面！')//el-form老出bug，无语
          return
        }
        if (valid) {
          //console.log('submit!')
          //简单的验证,不过这次当然要做路由守卫才到这
          ElMessageBox.prompt('星之内海，瞭望之台', '止步于此', {
            confirmButtonText: '回应',
            cancelButtonText: '离去',
          }).then(async ({value}) => {
            if(value == '无罪之人方可通过') {
              //后端校验账号权限
              if(await checkUserInfo()) {
                //blog数据已传入cover中，因为文件流在那里
                cover.value.files.submit()
                ElMessage.success('获得认可，提交成功！')
                setTimeout(() => {
                  router.replace('/home')
                }, 600)
              } else {
                ElMessage.error('无罪之人方可通过！')
                resetForm(ruleFormRef)
              }
            } else {
              ElMessage.error('未能通过认可，离去！')
            }
          }).catch(() => {
            ElMessage.info('认证取消')
          })
        }
      })
    }
    const resetForm = (ruleFormRef) => {
      ruleFormRef.resetFields()//这不就来了 
      //异类单独处理
      coverStatus = false
      cover.value.files.clearFiles()
    }
    const getCoverStatus = (status) => {
      coverStatus = status
    }
    const checkUserInfo = async () => {
      return new Promise((resolve) => {
        axios.get('http://localhost/api/getUserInfo', {
          headers: {
            Authorization: 'Bearer '+sessionStorage.getItem('token')
          }
        }).then(res => {
          let userInfo = res.data
          if(userInfo.authority == 'root') {
            resolve(true)
          } else {
            resolve(false)
          }
        }).catch(err => {
          console.log('未知错误！')
          console.log(err)
          resolve(false)
        })
      })
    }
    const mdUpload = async (files, callback) => {
      //Promise.all将多个promise对象整合为一个新的promise对象
      const result = await Promise.all(
        //map为数组中每个元素都修改为函数参数的返回值
        files.map(file => {
          return new Promise((resolve, reject) => {
            const form = new FormData()//表单相关，对象可储存文件流
            form.append('file', file)//追加文件
            axios.post('http://localhost/api/uploadImage', form,{
              headers: {
                'Content-Type': 'multipart/form-data'
              }
            }).then(res => {
                resolve(res)
              }).catch(err => {
                reject(err)
              })
            })
        })
      )
      callback(result.map((item) => item.data.url))
    }
    const mdHtml = (html) => {
      blog.html = html
    }
    
    return {
      ruleFormRef,
      blog,
      rules,
      cover,
      submitForm,
      resetForm,
      getCoverStatus,
      mdUpload,
      mdHtml
    }
  }
}
</script>

<style scoped>
  h1 {
    text-align: center;
    margin-bottom: 20px;
  }
  .edit-page {
    padding: 20px 100px;
  }
  .buttons {
    display: flex;
    justify-content: center;
    padding: 5px 0;
  }
</style>